package com.itheima.mall.web.oms;


import com.alibaba.nacos.common.utils.Objects;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mall.commons.page.PageResult;
import com.itheima.mall.commons.result.Result;
import com.itheima.mall.dubbo.api.oms.OrderItemService;
import com.itheima.mall.dubbo.api.oms.OrderOperateHistoryService;
import com.itheima.mall.dubbo.api.oms.OrderService;
import com.itheima.mall.entity.domain.oms.Order;
import com.itheima.mall.entity.domain.oms.OrderOperateHistory;
import com.itheima.mall.entity.dto.oms.OmsOrderDetail;
import com.itheima.mall.entity.vo.oms.DeliveryVo;
import com.itheima.mall.entity.vo.oms.OrderVo;
import com.itheima.mall.entity.vo.oms.ReceiverInfoVo;
import jnr.ffi.annotations.In;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.tags.form.LabelTag;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author qinglang
 * @since 2022-07-05
 */
@RestController
@RequestMapping("order")
@CrossOrigin(origins = "*")
public class OrderController {

       @DubboReference
       private OrderService orderService;

       @DubboReference
       private OrderItemService orderItemService;

       @DubboReference
       private OrderOperateHistoryService orderOperateHistoryService;

    /**
     * 查询订单
     * @param orderVo
     * @return
     */
    @GetMapping("list")
    public Result list(OrderVo orderVo){
      //分页
        Page<Order> orderPage = new Page<>(orderVo.getPageNum(), orderVo.getPageSize());
        //条件
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(orderVo.getOrderSn()!=null,Order::getOrderSn,orderVo.getOrderSn());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String createTime = orderVo.getCreateTime();
        LocalDateTime parse = null;
        if(createTime != null) {
            parse = LocalDate.parse(createTime, df).atStartOfDay();
        }
        lqw.eq(parse !=null,Order::getCreateTime,orderVo.getCreateTime());
        lqw.eq(orderVo.getOrderType() != null, Order::getOrderType, parse);
        lqw.eq(orderVo.getSourceType() != null, Order::getSourceType, orderVo.getSourceType());
        lqw.eq(orderVo.getStatus()!=null,Order::getStatus,orderVo.getStatus());
        lqw.like(orderVo.getReceiverKeyword() != null, Order::getReceiverName, orderVo.getReceiverKeyword());
        lqw.like(orderVo.getReceiverKeyword() != null, Order::getReceiverPhone, orderVo.getReceiverKeyword());
        lqw.orderByDesc(Order::getCreateTime);
        Page<Order> page = orderService.page(orderPage, lqw);
        PageResult init = PageResult.init(page.getRecords(), page.getCurrent(), page.getSize(), page.getTotal());
        return Result.success(init);
    }

       /**
        * 批量删除订单
         * @param ids
        * @return
        */
       @PostMapping("delete")
       public Result delete(@RequestParam List<Integer> ids){
           //订单表中设置状态为删除,逻辑删除
           orderService.update(new LambdaUpdateWrapper<Order>()
                   .set(Order::getDeleteStatus,1)
                   .in(Objects.nonNull(ids),Order::getId,ids));
              return Result.success();
       }

    /**
     * 批量关闭订单
     * @return
     */
   @PostMapping("update/close")//TODO 批量添加操作记录表
   public Result close(@RequestParam List<Integer> ids,String note){
        //修改订单表状态
       orderService.update(new LambdaUpdateWrapper<Order>()
               .set(Order::getStatus,4)
               .in(Objects.nonNull(ids),Order::getId,ids));
       //添加操作记录表
       OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
       for (Integer id : ids) {
           orderOperateHistory.setOrderId(id);
           orderOperateHistory.setOrderStatus(4);
           orderOperateHistory.setOperateMan("后台管理员");
           orderOperateHistory.setNote("订单关闭" + note);
//           orderOperateHistory.setCreateTime(LocalDateTime.now());
           orderOperateHistoryService.save(orderOperateHistory);
       }
       return Result.success();
   }

    /**
     * 批量发货
     * @return
     */
    @PostMapping("update/delivery")//TODO
   public  Result delivery(@RequestBody List<Order> orders){
        //判断订单状态是否为2,3(0,1允许操作,其他显示没有可操作的订单)
//        List<Long>orderIds=deliveryVos.stream().map(DeliveryVo::getOrderId).collect(Collectors.toList());
        List<Order> collect = orders.stream().map(item -> {
            Order order = orderService.getById(item.getId());
            Integer status = order.getStatus();
            if (status == 0 || status == 1) {
                return item;
            }
            return null;
        }).collect(Collectors.toList());
        orderService.updateBatchById(orders);
       /* //添加操作记录表
         OrderOperateHistory history = new OrderOperateHistory();
        for (Long orderId : orderIds) {
            history.setOrderId(orderId);
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(2);
            history.setNote("完成发货");
            history.setOperateMan("后台管理员");
        }
        orderOperateHistoryService.save(history);*/

        return Result.success();
   }

    /**
     * 修改订单费用信息
     *
     * @return
     */
    @PostMapping("/update/moneyInfo")
   public Result moneyInfo(@RequestBody Order order ){
        orderService.updateById(order);
              return Result.success();
   }

    /**
     * 备注订单
     * @return
     */
   @PostMapping("update/note")
   public Result note(Order order){
        orderService.updateById(order);
//    orderService.updateNote(id,note,status);
           return Result.success();
       }

    /**
     * 修改收货人信息
     * @param
     * @return
     */
    @PostMapping("update/receiverInfo")
 public Result receiverInfo(@RequestBody Order order){
     orderService.updateById(order);
       return Result.success();
 }

    /**
     * 获取订单详情：订单信息、商品信息、操作记录
     * @param id
     * @return
     */
    @GetMapping("{id}")
 public  Result detail(@PathVariable Long id){
    OmsOrderDetail omsOrderDetail = orderService.detail(id);
    return Result.success(omsOrderDetail);
 }
   }



